package ru.hh.school;

import ru.hh.school.commands.*;
import ru.hh.school.logging.Logger;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ChatRouter {
    private final Map<String, Command> commands;
    private final Pattern validateCommand;

    public ChatRouter(RoomManager roomManager, UserManager userManager, Logger logger) {
        List<Command> commands = new ArrayList<Command>();
        this.commands = new HashMap<String, Command>();
        commands.add(new NickCommand(logger, userManager));
        commands.add(new QuitCommand(logger, userManager));
        commands.add(new SendCommand(logger));
        commands.add(new ListRoomCommand(logger, roomManager));
        commands.add(new JoinRoomCommand(logger, roomManager));
        commands.add(new HelpCommand(logger, commands));

        //no str.join in Java :(
        //TODO but we have our own now
        StringBuilder cmds = new StringBuilder();
        for (Command c : commands) {
            this.commands.put(c.getCommand(), c);
            cmds.append(c.getCommand()).append("|");

        }
        String pattern = "(" + cmds.deleteCharAt(cmds.length() - 1).toString() + ")(.*)";
        validateCommand = Pattern.compile(pattern);
    }

    public void command(User user, String message) {
        Matcher matcher = validateCommand.matcher(message);
        if (matcher.matches()) {
            String command = matcher.group(1);
            String data = matcher.group(2).trim();
            commands.get(command).handle(user, data);
        } else {
            user.sendMessage("Incorrect command");
        }
    }
}